package com.example.flower_shop.service;

import com.example.flower_shop.entity.CustomerOrder;
import com.example.flower_shop.exception.BusinessException;
import lombok.Data;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentService {

    // 模拟支付记录存储
    private final Map<String, PaymentRecord> paymentRecords = new HashMap<>();

    public PaymentResult createPayment(CustomerOrder order) {
        // 生成支付记录
        PaymentRecord record = new PaymentRecord();
        record.setOrderNo(order.getOrderNo());
        record.setAmount(order.getTotalAmount());
        record.setStatus(PaymentStatus.PENDING);
        record.setCreateTime(LocalDateTime.now());

        paymentRecords.put(order.getOrderNo(), record);

        // 返回支付信息
        return new PaymentResult(
                order.getOrderNo(),
                order.getTotalAmount(),
                "http://example.com/pay/" + order.getOrderNo() // 模拟支付链接
        );
    }

    public void mockPayment(String orderNo, BigDecimal amount) {
        PaymentRecord record = paymentRecords.get(orderNo);
        if (record == null) {
            throw new BusinessException("PAYMENT_NOT_FOUND", "支付记录不存在");
        }

        if (record.getStatus() != PaymentStatus.PENDING) {
            throw new BusinessException("INVALID_PAYMENT_STATUS", "支付状态不正确");
        }

        if (record.getAmount().compareTo(amount) != 0) {
            throw new BusinessException("INVALID_AMOUNT", "支付金额不正确");
        }

        record.setStatus(PaymentStatus.SUCCESS);
        record.setPayTime(LocalDateTime.now());
    }

    public PaymentStatus getPaymentStatus(String orderNo) {
        PaymentRecord record = paymentRecords.get(orderNo);
        return record != null ? record.getStatus() : null;
    }

    @Data
    private static class PaymentRecord {
        private String orderNo;
        private BigDecimal amount;
        private PaymentStatus status;
        private LocalDateTime createTime;
        private LocalDateTime payTime;
    }

    public enum PaymentStatus {
        PENDING, // 待支付
        SUCCESS, // 支付成功
        FAILED // 支付失败
    }

    @Data
    public static class PaymentResult {
        private final String orderNo;
        private final BigDecimal amount;
        private final String payUrl;
    }
}